﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AutoWindowsSize; //窗口自适应
namespace h1
{
    public partial class Form_data : Form
    {
        Font defaultFont;
        Color defaultColor;
        CurrencyManager cm = null;
        AutoAdaptWindowsSize AutoSize; //窗口自适应
        public Form_data()
        {
            InitializeComponent();
        }
        List<School> schools = new List<School>();
        List<Class> classes = new List<Class>();
        List<Student> students = new List<Student>();
        private void Form_data_Load(object sender, EventArgs e)
        {
            schools.Clear();
            classes.Clear();
            students.Clear();
            comboBox1.SelectedIndex = 0;
            defaultFont = dataGridView1.DefaultCellStyle.Font;
            defaultColor = dataGridView1.DefaultCellStyle.ForeColor;
            using (var db = new Sqlite())
            {
                foreach (var school in db.Schools)
                {
                    
                }
            }
            show(0);
            AutoSize = new AutoAdaptWindowsSize(this);//窗口自适应
        }

        private void show(int tabel)
        {
            string connString = "server=localhost;port=3306;user=root;password=23364464178; database=homework1;";
            try
            {
                using (MySqlConnection connection = new MySqlConnection(connString))
                {
                    string sql = "";
                    switch (tabel)
                    {
                        case 0:
                            sql = "SELECT * FROM Schools";
                            break;
                        case 1:
                            sql = "SELECT * FROM Classes";
                            break;
                        case 2:
                            sql = "SELECT * FROM Students";
                            break;
                        case 3:
                            sql = "SELECT * FROM users";
                            break;
                    }
                    connection.Open();
                    using (MySqlDataAdapter sda = new MySqlDataAdapter(sql, connection))
                    {
                        try
                        {
                            DataSet ds = new DataSet();
                            sda.Fill(ds);
                            dataGridView1.DataSource = ds.Tables[0];
                            cm = (CurrencyManager)BindingContext[dataGridView1.DataSource];
                        }
                        catch (Exception ex)
                        {
                            Form_message fm = new Form_message("数据库数据读取出错", "出错描述：" + ex.Message);
                            fm.ShowDialog();
                        }
                    }
                }
            }catch(Exception ex)
            {
                Form_message fm = new Form_message("数据库数据连接出错", "出错描述：" + ex.Message);
                fm.ShowDialog();
            }
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch(comboBox1.SelectedIndex)
            {
                case 0:
                    show(0);
                    break;
                case 1: 
                    show(1); 
                    break;
                case 2: 
                    show(2); 
                    break;
                case 3:
                    show(3);
                    break;
                default:
                    show(0);
                    break;
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            FileStream fout = new FileStream(@"log.txt", FileMode.Append, FileAccess.Write);
            StreamWriter bw = new StreamWriter(fout);
            bw.WriteLine("******************************************");
            bw.WriteLine("当前时间为："+DateTime.Now.ToString());
            bw.WriteLine($"正在修改表格[{comboBox1.Text}]：");
            bw.WriteLine("保存前：");
            string connString = "server=localhost;port=3306;user=root;password=23364464178; database=homework1;";
            using (MySqlConnection connection = new MySqlConnection(connString))
            {
                DataTable dt = (DataTable)dataGridView1.DataSource;
                string sql = "";
                switch (comboBox1.SelectedIndex)
                {
                    case 0:
                        sql = "SELECT * FROM Schools";
                        break;
                    case 1:
                        sql = "SELECT * FROM Classes";
                        break;
                    case 2:
                        sql = "SELECT * FROM Students";
                        break;
                    case 3:
                        sql = "SELECT * FROM users";
                        break;
                    default:
                        sql = "SELECT * FROM Schools";
                        break;
                }
                connection.Open();
                using (MySqlDataAdapter sda = new MySqlDataAdapter(sql, connection))
                {
                    MySqlCommandBuilder builder = new MySqlCommandBuilder(sda);
                    try
                    {
                        DataSet ds=new DataSet();
                        sda.Fill(ds);
                        foreach(DataRow dr in ds.Tables[0].Rows)
                        {
                            bw.Write("||");
                            foreach(DataColumn cls in ds.Tables[0].Columns)
                            {
                                bw.Write(cls.ToString() + "：" + ((dr[cls.ToString()].ToString() == "") ? "（空）" : dr[cls.ToString()].ToString()) + "\t||");
                            }
                            bw.WriteLine();
                        }
                        sda.Update(dt);
                        bw.WriteLine("保存后：");
                        foreach (DataRow dr in dt.Rows)
                        {
                            bw.Write("||");
                            foreach (DataColumn cls in dt.Columns)
                            {
                                bw.Write(cls.ToString() + "：" + ((dr[cls.ToString()].ToString()=="")?"（空）":dr[cls.ToString()].ToString()) + "\t||");
                            }
                            bw.WriteLine();
                        }
                        bw.WriteLine("保存成功！");
                        Form_message fm= new Form_message("保存成功！"," ");
                        fm.ShowDialog();
                    }
                    catch(Exception ex)
                    {
                        bw.WriteLine("保存失败！");
                        Form_message fm = new Form_message("数据库更新出错", "出错描述：" + ex.Message);
                        fm.ShowDialog();
                    }
                    bw.WriteLine("操作结束，当前时间为："+DateTime.Now.ToString());
                    bw.WriteLine("******************************************");
                    bw.Close();
                }
            }
            
        }

        private void 恢复默认ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dataGridView1.DefaultCellStyle.Font = defaultFont;
            dataGridView1.ColumnHeadersDefaultCellStyle.Font = defaultFont;
        }

        private void 设置ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            fontDialog1.ShowDialog();
            if (!fontDialog1.FontMustExist)
            {
                dataGridView1.DefaultCellStyle.Font = fontDialog1.Font;
                dataGridView1.ColumnHeadersDefaultCellStyle.Font = fontDialog1.Font;
            }
        }

        private void 设置ToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            colorDialog1.ShowDialog();
            if (colorDialog1.Color!=null)
            {
                dataGridView1.DefaultCellStyle.ForeColor = colorDialog1.Color;
                dataGridView1.ColumnHeadersDefaultCellStyle.ForeColor = colorDialog1.Color;
            }
        }

        private void 恢复默认ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            dataGridView1.DefaultCellStyle.ForeColor = defaultColor;
            dataGridView1.ColumnHeadersDefaultCellStyle.ForeColor = defaultColor;
        }



        private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if(关闭ToolStripMenuItem.Text=="关闭")
            dataGridView1.Rows.Remove(dataGridView1.SelectedRows[0]);
            /*string p_ID = dataGridView1.SelectedRows[0].Cells[comboBox1.Text+"ID"].ToString();
            Form_details form_Details = new Form_details(comboBox1.SelectedIndex, p_ID);
            form_Details.ShowDialog();*/
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (comboBox1.Text == "")
            {
                errorProvider1.SetError(comboBox1, "请先选择表格");
            }
            else
            {
                errorProvider1.Clear();
                Form_Choose fc = new Form_Choose(this, comboBox1.SelectedIndex);
                fc.ShowDialog();
            }
        }
        public void show(DataSet ds)
        {
            dataGridView1.DataSource= ds.Tables[0];
            cm = (CurrencyManager)BindingContext[dataGridView1.DataSource];
        }
        public void show(DataTable dt)
        {
            dataGridView1.DataSource = dt;
            cm = (CurrencyManager)BindingContext[dataGridView1.DataSource];
        }
        public void show(List<string> ids)
        {
            cm.SuspendBinding();
            for (int i=0;i<dataGridView1.Rows.Count-1;i++)
            {
                if (!ids.Contains(dataGridView1.Rows[i].Cells[comboBox1.Text + "ID"].Value))
                {
                    dataGridView1.Rows[i].Visible = false;
                }
            }
            cm.ResumeBinding();
        }

        private void 表格字体颜色ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 关闭ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (关闭ToolStripMenuItem.Text == "关闭")
            {
                关闭ToolStripMenuItem.Text = "开启";
            }
            else
            {
                关闭ToolStripMenuItem.Text = "关闭";
            }
        }

        private void 打开日志文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("explorer.exe", @".\log.txt");
        }

        private void 清空日志文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FileStream fout = new FileStream(@"log.txt", FileMode.Create, FileAccess.Write);
            StreamWriter bw = new StreamWriter(fout);
            bw.Write("");
            bw.Close();
            Form_message form_message = new Form_message("提示：", "日志文件已清空！");
            form_message.ShowDialog();
        }

        private void Form_data_SizeChanged(object sender, EventArgs e)
        {
            if (AutoSize != null)
            {
                AutoSize.FormSizeChanged();
            }
        }
    }
}
